package com.qqtech.qquan.send.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.common.collect.Lists;
import com.qqtech.agent.context.AdminPage;
import com.qqtech.core.common.enums.YesNoEnum;
import com.qqtech.core.common.util.StringUtil;
import com.qqtech.core.common.util.TimeUtil;
import com.qqtech.core.frame.model.PageKit;
import com.qqtech.core.frame.model.PageOrder;
import com.qqtech.core.frame.model.Result;
import com.qqtech.qquan.mall.enums.MallSupplierStatusDictEnum;
import com.qqtech.qquan.mall.model.MallSupplier;
import com.qqtech.qquan.mall.model.MallSupplierQuery;
import com.qqtech.qquan.mall.service.MallSupplierService;
import com.qqtech.qquan.order.model.OrderItemVo;
import com.qqtech.qquan.order.service.OrderItemService;
import com.qqtech.qquan.send.model.SendDeliveryOrder;
import com.qqtech.qquan.send.model.SendDeliveryOrderItem;
import com.qqtech.qquan.send.model.SendDeliveryOrderItemVo;
import com.qqtech.qquan.send.model.SendDeliveryOrderQuery;
import com.qqtech.qquan.send.model.SendDeliveryOrderVo;
import com.qqtech.qquan.send.service.SendDeliveryOrderItemService;
import com.qqtech.qquan.send.service.SendDeliveryOrderService;
import com.qqtech.qquan.sys.controller.BaseAgentController;
import com.qqtech.qquan.sys.enums.SysConst;
import com.qqtech.qquan.sys.model.SysParam;
import com.qqtech.qquan.sys.service.SysParamService;
import com.qqtech.qquan.util.ExcelUtil;

@Controller
@RequestMapping(value = "/send/deliveryOrder")
public class SendDeliveryOrderController extends BaseAgentController {
	
	@Resource
	private SendDeliveryOrderService sendDeliverOrderService;
	@Resource
	private SendDeliveryOrderItemService sendDeliverOrderItemService;
	
	@Resource
	private OrderItemService orderItemService;
	
	@Resource
	private MallSupplierService mallSupplierService;	
	@Resource
	private SysParamService sysParamService;
	
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		MallSupplierQuery supplierQuery = new MallSupplierQuery();
		supplierQuery.setStatus(MallSupplierStatusDictEnum.NORMAL.getCode());
		supplierQuery.setIsShow(YesNoEnum.YES.getCode());
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.ASC, "id"));
		List<MallSupplier> mallSupplierList = mallSupplierService.queryList(supplierQuery, pageKit);
		model.addAttribute("mallSupplierList", mallSupplierList);
		return "/send/deliveryOrder-list";
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public AdminPage list(SendDeliveryOrderQuery query, HttpServletRequest request,	HttpServletResponse response) {
		AdminPage adminPage = new AdminPage();
		String rows = (String) request.getParameter("rows"); // 每页条数
		query.setSize(Integer.valueOf(rows));
		query.setCommunityId(super.getCurrCommunityId());//当前后台用户的社区id
		Pageable pageKit = new PageKit(query.getPage(), query.getSize(),new PageOrder(Direction.DESC, "newAt"));
		Page<SendDeliveryOrderVo> page = sendDeliverOrderService.queryPageListAdmin(query,pageKit);
		adminPage.setRows(page.getContent());
		adminPage.setTotal(Integer.valueOf(page.getTotalElements() + ""));
		return adminPage;
	}

	@RequestMapping(value = "/detail")
	public String detail(SendDeliveryOrderQuery query, Model model) {
		SendDeliveryOrder deliveryOrder = sendDeliverOrderService.getById(query.getId());
		List<OrderItemVo> orderItemList = Lists.newArrayList();
		if (deliveryOrder != null) {
			model.addAttribute("deliveryOrder", deliveryOrder);
			
			List<SendDeliveryOrderItemVo> deliveryOrderItemList = sendDeliverOrderItemService.getDeliveryOrderItemList(deliveryOrder.getId());
			if(deliveryOrderItemList!=null && deliveryOrderItemList.size()>0){
				List<Integer> includeIds = Lists.newArrayList();
				for(SendDeliveryOrderItem item : deliveryOrderItemList){
					includeIds.add(item.getOrderItemId());
				}
				if(includeIds!=null && includeIds.size()>0){
					orderItemList = orderItemService.getListByItemIds(includeIds);
				}
			}
			model.addAttribute("orderItemList", orderItemList);
		}
		return "/send/deliveryOrder-detail";
	}
	
	@RequestMapping(value = "/export2Excel", method = RequestMethod.POST)
	@ResponseBody
	public Result export2Excel(SendDeliveryOrderQuery query, HttpServletRequest request, HttpServletResponse response) {
		Result ret = new Result();
		query.setCommunityId(super.getCurrCommunityId());//当前后台用户的社区id
		Pageable pageKit = new PageKit(1, Integer.MAX_VALUE, new PageOrder(Direction.DESC, "newAt"));
		int count = sendDeliverOrderService.queryCount(query);
		SysParam sysParam = sysParamService.getByKey(SysConst.PARAM_SYS_EXPORT_TOEXCEL_MAXROWS);
		if (sysParam != null && StringUtil.isNotBlank(sysParam.getValue())) {
			int maxExportRows = Integer.valueOf(sysParam.getValue());
			if(count > maxExportRows){
				ret.addErr("导出数量不能超过"+maxExportRows+"行!");
				return ret;
			}
		}
		Page<SendDeliveryOrderVo> page = sendDeliverOrderService.queryPageListAdmin(query, pageKit);
		List<SendDeliveryOrderVo> deliveryOrderList =  page.getContent();//不分页
		
		List<Map<String,Object>> list=createExcelRecord(deliveryOrderList);
    	String columnNames[]={"订单号","订单名称","社区名称","配送单号","接单时间","取件状态","配送状态","配送时间","商品总数量",
    						  "买家昵称","联系人","联系电话","收货地址",
    						  "供应商","供应商电话","供应商地址"};//列名
        String keys[] =  {"orderNo","orderTitle","communityName","id","strNewAt","strPickupStatus","deliveryStatus","strDeliveryAt","quantityTotal",
        		          "userNick","consignee","phone","address",
        				  "supplierName","supplierPhone","supplierAddress"};//map中的key
        String fileName="配送单"+TimeUtil.getStringTimeByFormat(TimeUtil.now(),TimeUtil.DATE_TIME_FORMAT).replaceAll(" ", "T");
        ExcelUtil.ExcelSingleOutputStream(list,keys,columnNames,fileName,request,response);
        list = null;
        return ret;
	}
	
    private List<Map<String, Object>> createExcelRecord(List<SendDeliveryOrderVo> deliveryOrderList) {
        List<Map<String, Object>> listmap = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("sheetName", "配送单");
        listmap.add(map);
        SendDeliveryOrderVo deliveryOrder=null;
        for (int j = 0; j < deliveryOrderList.size(); j++) {
        	deliveryOrder=deliveryOrderList.get(j);
            Map<String, Object> mapValue = new HashMap<String, Object>();
            mapValue.put("orderNo", deliveryOrder.getOrderNo());
            mapValue.put("orderTitle", deliveryOrder.getOrderTitle());
            mapValue.put("communityName", deliveryOrder.getCommunityName());
            mapValue.put("id", deliveryOrder.getId());
            mapValue.put("strNewAt", deliveryOrder.getStrNewAt());
            mapValue.put("strPickupStatus", deliveryOrder.getStrPickupStatus());
            mapValue.put("deliveryStatus", deliveryOrder.getStrDeliveryStatus());
            mapValue.put("strDeliveryAt", deliveryOrder.getStrDeliveryAt());
            mapValue.put("quantityTotal", deliveryOrder.getQuantityTotal());
            mapValue.put("userNick", deliveryOrder.getUserNick());
            mapValue.put("consignee", deliveryOrder.getConsignee());
            mapValue.put("phone", deliveryOrder.getPhone());
            mapValue.put("address", deliveryOrder.getAddress());
            mapValue.put("supplierId", deliveryOrder.getSupplierId());
            mapValue.put("supplierName", deliveryOrder.getSupplierName());
            mapValue.put("supplierPhone", deliveryOrder.getSupplierPhone());
            mapValue.put("supplierAddress", deliveryOrder.getSupplierAddress());
            listmap.add(mapValue);
        }
        return listmap;
    }
}
